package com.powernode.lambda.stream;

import com.powernode.lambda.Student;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 测试stream相关Api
 * mapping先转换，再统计counting、maxBy、summingInt、averagingInt
 *
 */
public class Stream11 {
    public static void main(String[] args) {
        Stream<Student> stream = Stream.of(
                new Student("张无忌", 26, "男"),
                new Student("赵敏", 22, "女"),
                new Student("周芷若", 21, "女"),
                new Student("女波斯圣使", 30, "女"),
                new Student("灭绝师太", 30, "女"),
                new Student("张三丰", 100, "男")
        );

        /**
         * mapping：先转换，再收集
         * 按照名字长度分组，分组后只保留age
         * groupingBy先按照名字长度分组，然后把student转化成age，再收集成list
         */
//        Map<Integer, List<Integer>> collect = stream.collect(
//                Collectors.groupingBy((x -> x.getName().length()), Collectors.mapping(x->x.getAge(),Collectors.toList())));
//        for (Map.Entry<Integer, List<Integer>> entry : collect.entrySet()) {
//            System.out.println(entry);
//        }

        /**
         * counting:先按照名字长度分组，分组后求每组个数
         */
//        Map<Integer, Long> collect = stream.collect(
//                Collectors.groupingBy((x -> x.getName().length()), Collectors.counting()));
//        for (Map.Entry<Integer, Long> entry : collect.entrySet()) {
//            System.out.println(entry);
//        }

        /**
         * maxBy:先按照名字长度分组，分组后求每组年龄最大的人
         */
//        Map<Integer, Optional<Student>> collect = stream.collect(
//                Collectors.groupingBy((x -> x.getName().length()),
//                        Collectors.maxBy(Comparator.comparingInt(x -> x.getAge()))));
//        for (Map.Entry<Integer, Optional<Student>> entry : collect.entrySet()) {
//            System.out.println(entry);
//        }

        /**
         * summingInt:先按照名字长度分组，分组后求每组年龄之和
         */
//        Map<Integer, Integer> collect = stream.collect(
//                Collectors.groupingBy(
//                        (x -> x.getName().length()), Collectors.summingInt(x -> x.getAge())));
//        for (Map.Entry<Integer, Integer> entry : collect.entrySet()) {
//            System.out.println(entry);
//        }
        /**
         * averagingInt:先按照名字长度分组，分组后求每组年龄平均值
         */
        Map<Integer, Double> collect = stream.collect(
                Collectors.groupingBy(
                        (x -> x.getName().length()), Collectors.averagingInt(x -> x.getAge())));
        for (Map.Entry<Integer, Double> entry : collect.entrySet()) {
            System.out.println(entry);
        }
    }

}
